package com.rent.controller;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rent.annotation.NoAuth;
import com.rent.beans.Result;
import com.rent.beans.request.LoginRequest;
import com.rent.entity.WechatUser;
import com.rent.model.LoginResultModel;
import com.rent.model.WechatUserModel;
import com.rent.service.WechatUserService;
import com.rent.utils.JwtUtil;
import com.rent.utils.WechatAppIdUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * 登录
 *
 * @author lihaoyang
 * @date 2021/1/23
 */
@Api(tags = "用户登录")
@Slf4j
@RestController
@RequestMapping("api")
public class LoginController {


    @Autowired
    WechatUserService wechatUserService;

//    @Autowired
//    RedisUtil redisUtil;

    @NoAuth
    @ApiOperation("登录接口")
    @GetMapping("openid/get")
    public Result getOpenId(@RequestParam(name = "code") String code) throws Exception {
        System.out.println("进来拉~~~~~~~~~~~~~~");
        System.out.println("code= " + code);
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        url += "?appid=wx2fb351b408b75d59";//自己的appid
        url += "&secret=d66ef6157cbbe92721611a8cac4da7b9";//自己的appSecret
        url += "&js_code=" + code;
        url += "&grant_type=authorization_code";
        url += "&connect_redirect=1";
        String res = null;
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // DefaultHttpClient();
        HttpGet httpget = new HttpGet(url);    //GET方式
        CloseableHttpResponse response = null;
        // 配置信息
        RequestConfig requestConfig = RequestConfig.custom()          // 设置连接超时时间(单位毫秒)
                .setConnectTimeout(5000)                    // 设置请求超时时间(单位毫秒)
                .setConnectionRequestTimeout(5000)             // socket读写超时时间(单位毫秒)
                .setSocketTimeout(5000)                    // 设置是否允许重定向(默认为true)
                .setRedirectsEnabled(false).build();           // 将上面的配置信息 运用到这个Get请求里
        httpget.setConfig(requestConfig);                         // 由客户端执行(发送)Get请求
        response = httpClient.execute(httpget);                   // 从响应模型中获取响应实体
        HttpEntity responseEntity = response.getEntity();
        System.out.println("响应状态为:" + response.getStatusLine());
        if (responseEntity != null) {
            res = EntityUtils.toString(responseEntity);
            System.out.println("响应内容长度为:" + responseEntity.getContentLength());
            System.out.println("响应内容为:" + res);
        }
        // 释放资源
        if (httpClient != null) {
            httpClient.close();
        }
        if (response != null) {
            response.close();
        }
        JSONObject jo = JSON.parseObject(res);
        String openid = jo.getString("openid");
        System.out.println("openid" + openid);
        return Result.OK(openid);
    }


    @NoAuth
    @ApiOperation("微信登录接口仅限调试")
    @GetMapping("wxLogin/loginByCodeDev")
    public Result wxLoginByCodeDev(@RequestParam(name = "code") String code,
                                   @RequestParam(name = "appid") String appid,
                                   @RequestParam(name = "secret") String secret) throws Exception {
        return Result.OK(this.wechatUserService.wechatLogin(code, appid, secret));
    }


    @NoAuth
    @ApiOperation("微信登录接口仅限调试")
    @GetMapping("wxLogin/test")
    public Result wxLoginByCodeDev() throws Exception {
        LoginResultModel loginResultModel=new LoginResultModel();
        loginResultModel.setJwtToken("aaaaaa");
        loginResultModel.setWechatUserModel(new WechatUserModel());
       loginResultModel.setOpenId("eeee");
        return Result.OK(loginResultModel);
    }


    @NoAuth
    @ApiOperation("微信登录接口")
    @GetMapping("wxLogin/loginByCode")
    public Result wxLoginByCode(@RequestParam(name = "code") String code) throws Exception {

        return Result.OK(this.wechatUserService.wechatLogin(code, WechatAppIdUtil.appid, WechatAppIdUtil.secret));
    }


    @PostMapping("wxLogin")
    public Result wxLogin(@RequestBody LoginRequest loginRequest) throws Exception {
        log.info("loginRequest: " + JSONObject.toJSONString(loginRequest));
        //根据openId查询是否存在，不存在 insert ,存在update
        WechatUser wechatUser = wechatUserService.getByOpenId(loginRequest.getOpenId());
        if (Objects.isNull(wechatUser)) {
            wechatUser = new WechatUser();
            BeanUtil.copyProperties(loginRequest, wechatUser);
            wechatUser.setStatus(1);
            wechatUserService.save(wechatUser);
        }
//        }else{
//            UpdateWrapper<WechatUser> updateWrapper = new UpdateWrapper<>();
//            updateWrapper.eq("sex",loginRequest.getSex());
//            updateWrapper.eq("headImg",loginRequest.getHeadImg());
//            updateWrapper.eq("nickname",loginRequest.getNickname());
//            WechatUser user = new WechatUser();
//            user.setOpenId(user.getOpenId());
//            wechatUserService.update(user, updateWrapper);
//        }
        //生成JWT
        String jwt = JwtUtil.getJWT(wechatUser.getOpenId());
        return Result.OK(jwt);
    }
}

